package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.ServletObj;
import com.project.bean.UserObjBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@ServletObj(url="/two")
public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        List<UserObjBean> userList = Arrays.asList(
                new UserObjBean(1,"张三", LocalDate.parse("1998-02-03")),
                new UserObjBean(5,"李四", LocalDate.parse("1997-11-12")),
                new UserObjBean(6,"王二", LocalDate.parse("1995-06-26"))
        );

        ObjectMapper om = new ObjectMapper();
        //注册新日期类型
        om.registerModule(new JavaTimeModule());
        //将对象转化为json格式字符串
//        String str = om.writeValueAsString(userList);
//
//        resp.getWriter().print(str);
        //将对象转化为json字符串输出到客户端
        om.writeValue(resp.getWriter(), userList);
    }
}
